from django.shortcuts import render,redirect
from django.views import View
from django.http import HttpResponse
from apps.goods.models import *
from apps.order.models import OrderGoods,OrderInfo
from django.urls import reverse
from django.core.cache import cache
from django.core.paginator import Paginator
from django_redis import get_redis_connection
from celery_tasks.tasks import *
# Create your views here.

class IndexView(View):
    """首页"""
    def get(self,request):
        #尝试从缓存中获取数据
        content=cache.get("index_page_data")
        if content is None:
            #获取首页商品分类
            types=GoodsType.objects.all()
            goods_type=IndexTypeGoodsBanner.objects.all()

            #获取首页banner轮播图
            banners=IndexGoodsBanner.objects.all().order_by("index")

            #获取首页活动信息
            promotion=IndexPromotionBanner.objects.all().order_by("index")

            #获取分类详情
            for type in types:
                title_goods=goods_type.filter(type=type,display_type=0)
                image_goods = goods_type.filter(type=type,display_type=1)
                type.title_goods=title_goods
                type.image_goods=image_goods

            content={
                "types":types,
                "banners":banners,
                "promotion":promotion,
            }

            #设置缓存
            cache.set("index_page_data",content,3600)

        # 获取购物车数目
        cart_num = 0
        user = request.user
        if user.is_authenticated:
            # 用户已登入
            conn = get_redis_connection("default")
            cart_num = conn.hlen("cart_%d" % user.id)
        content.update(cart_num=cart_num)

        return render(request,"index.html",content)

# /goods/detail/id
class GoodsDetail(View):
    """商品详情"""
    def get(self,request,id):
        try:
            # 获取对应商品信息
            sku=GoodsSKU.objects.get(id=id)
        except GoodsSKU.DoesNotExist:
            return redirect(reverse("goods:index"))

        #获取商品分类信息
        types=GoodsType.objects.all()

        #获取前5条新品信息
        news=GoodsSKU.objects.filter(type=sku.type).order_by("-create_time")[:2]

        #获取其他规格商品
        same_skus=GoodsSKU.objects.filter(goods=sku.goods).exclude(id=id)

        cart_num=0
        user=request.user
        if user.is_authenticated:
            #用户已登入
            # 获取购物车数目
            conn=get_redis_connection("default")
            cart_num=conn.hlen("cart_%d" % user.id)

            #添加历史浏览记录
            history_key="history_key_%d" % user.id
            conn.lrem(history_key,0,id)
            conn.lpush(history_key,id)

            #保存最新的50条记录
            conn.ltrim(history_key,0,50)

        #获取订单评论
        sku_orders=OrderGoods.objects.filter(sku=sku)
        sku
        content={
            "sku":sku,
            "cart_num":cart_num,
            "news":news,
            "same_skus":same_skus,
            "types":types,
            "sku_orders":sku_orders
        }
        return render(request,"detail.html",content)


    def post(self,request):
        pass

# /goods/list/类别id/页码/排序方式
class List(View):
    """商品列表页"""
    def get(self,request,type_id,page_num=1):
        type_id=int(type_id)

        sort=request.GET.get("sort")

        if page_num=="":
            page_num=0
        else:
            page_num=int(page_num)

        # 获取商品分类信息
        types = GoodsType.objects.all()
        try:
            type = types.get(id=type_id)
        except GoodsType.DoesNotExist:
            return redirect(reverse("goods:index"))

        #获取对应类别的商品
        if sort=="price":
            skus = GoodsSKU.objects.filter(type=type).order_by("price")
        elif sort=="hot":
            skus = GoodsSKU.objects.filter(type=type).order_by("-sales")
        else:
            skus = GoodsSKU.objects.filter(type=type).order_by("-id")

        #获取分页
        p = Paginator(skus, 1)
        if page_num >p.num_pages:
            page_num=1

        page=p.page(page_num)

        # 1.总页数小于5页，页面上显示所有页码
        # 2.如果当前页是前3页，显示1-5页
        # 3.如果当前页是后3页，显示后5页
        # 4.其他情况，显示当前页的前2页，当前页，当前页的后2页
        if p.num_pages<=5:
            sku_pages=range(1,p.num_pages+1)
        elif page_num<=3:
            sku_pages=range(1,6)
        elif p.num_pages-page_num>=3:
            sku_pages=range(p.num_pages-4,p.num_pages+1)
        else:
            sku_pages=range(page_num-2,page_num+3)

        # 获取前5条新品信息
        news = GoodsSKU.objects.filter(type=type).order_by("-create_time")[:2]

        cart_num = 0
        user = request.user
        if user.is_authenticated:
            # 用户已登入
            # 获取购物车数目
            conn = get_redis_connection("default")
            cart_num = conn.hlen("cart_%d" % user.id)

        content={
            "type":type,
            "types":types,
            "page":page,
            "news":news,
            "cart_num":cart_num,
            "sort":sort,
            "sku_pages":sku_pages
        }
        return render(request,"list.html",content)

def test(request):
    generate_static_index_html.delay()
    return HttpResponse("ok")